import { Form, Input, Select, Space, Button, DatePicker } from "antd";
import { SearchOutlined } from "@ant-design/icons";
import ThePagination from "@/components/ThePagination";
import TheTable from "@/components/TheTable";
import TheButton from "@/components/TheButton";
import React, { useEffect, useRef, useState } from "react";
import "../style/style.less";
import { apiGetCommodityList, apiGetCalssify, apiProductInfoDel, apiProductInfoUpdateState } from '@/request/commodity'
import TheImage from '@/components/TheImage'
import _ from 'lodash'
import { getDateTime3 } from '@/utils/getDate'
import { exportSheetTable, exportTableModal } from '@/utils/exportTable'
import moment from "moment";

const { RangePicker } = DatePicker;

const SearchHeader = ({ setSearchValue, exportSheet, exportLoading }) => {
  const formRef = useRef()
  const [options, setOptions] = useState([])
  useEffect(async () => {
    if(localStorage.getItem('searchValue')){
      let search = JSON.parse(localStorage.getItem('searchValue'))
      formRef.current.setFieldsValue({
        goodsName: search.goodsName? search.goodsName: '',
        goodsId: search.goodsId? search.goodsId: '',
        materialId:search.materialId?search.materialId:"",
        classifyId: search.classifyId? search.classifyId: null,
        time: search.createTimeStart?[moment(search.createTimeStart),moment(search.createTimeEnd)] :[]
      })
    }
    let res = await apiGetCalssify()
    if (res.code === 0 && res.data) {
      let options = res.data.map(v => {
        return {
          value: v.productClassifyId,
          label: v.productClassifyName
        }
      })
      setOptions(options)
    }
  }, [])
  const reset = () => {
    formRef.current.setFieldsValue({
      productName: '',
      productId: '',
      classifyId: null,
      materialId:"",
      time: []
    })
    localStorage.removeItem('searchValue')
    setSearchValue({})
  };
  const onFinish = values => {
    if (values.time && values.time.length) {
      values.createTimeStart = getDateTime3(values.time[0])
      values.createTimeEnd = getDateTime3(values.time[1])
    }
    delete (values.time)
    _.forIn(values, (v, k) => {
      if (!v) {
        delete (values[k])
      }
    })
    setSearchValue(values)
  }
  const exportTable = () => {
    exportSheet()
  }
  return (
    <Form ref={formRef} onFinish={onFinish} layout="inline">
      <Form.Item name={"productName"}>
        <Input
          style={{ width: 120 }}
          suffix={<SearchOutlined />}
          placeholder={"商品名称"}
        />
      </Form.Item>
      <Form.Item name={"productId"} rules={[{pattern: /^[0-9]+$/, message: '只能输入数字'}]} >
        <Input
          style={{ width: 120 }}
          suffix={<SearchOutlined />}
          placeholder={"商品ID"}
        />
      </Form.Item>
      <Form.Item name={"materialId"} label="物料ID">
      <Input
          style={{ width: 120 }}
          suffix={<SearchOutlined />}
          placeholder={"物料ID"}
        />
      </Form.Item>
      <Form.Item name={"classifyId"} label="所属类目">
        <Select allowClear
          style={{ width: 160 }}
          options={options}
          placeholder={"所属类目"}
        />
      </Form.Item>
      <Form.Item name={"time"} label="上架时间">
        <RangePicker />
      </Form.Item>
      <Form.Item>
        <Space size="small" style={{ marginLeft: 10 }}>
          <Button type="primary" htmlType="submit">
            查询
          </Button>
          <Button onClick={reset}>重置</Button>
          <TheButton size="middle" type="default" hasPermi={['commodity:library:exportGoodBySku']} loading={exportLoading} onClick={exportTable}>导出</TheButton>
        </Space>
      </Form.Item>
    </Form>
  );
};

class Library extends React.Component {
  state = {
    columns: [
      {
        title: "商品ID",
        dataIndex: "productId",
        key: "productId",
      },
      {
        title: "商品名称",
        dataIndex: "productName",
        key: "productName",
      },
      {
        title: "商品图片",
        dataIndex: "productShowImages",
        key: "productShowImages",
        render: (text, record) => {
          let str = record.productShowImages.split(',')[0]
          return <TheImage src={str} width={80} height={80} />
        }
      },
      {
        title: "所属分类",
        dataIndex: "productClassifyName",
        key: "productClassifyName",
      },
      {
        title: "商品原价",
        dataIndex: "originalPrice",
        key: "originalPrice",
        render: (text, record) => {
          return <React.$Price price={record.originalPrice || 0} />
        }
      },
      {
        title: "商品现价",
        dataIndex: "currentPrice",
        key: "currentPrice",
        render: (text, record) => {
          return <React.$Price price={record.currentPrice || 0} />
        }
      },
      {
        title: "审核状态",
        render: (text, record) => {
          return "待审核"
        }
      },
      {
        title: "补录状态",
        dataIndex: 'importStatus',
        render: (text, record) => {
          return text === 'N' ? <span style={{ color: 'red' }}>需要补录</span> : <span>不需要补录</span>
        }
      },
      {
        title: "创建时间",
        dataIndex: "updateTime",
        key: "updateTime",
      },
      {
        title: "上次操作时间",
        dataIndex: "lastUpdateTime",
        key: "lastUpdateTime",
        render:(text, record)=>{
          return record.lastUpdateTime ? record.lastUpdateTime : "/"
        }
      },
      {
        title: "操作人",
        dataIndex: "userName",
        key: "userName",
        render:(text, record)=>{
          return record.userName ? record.userName : "/"
        }
      },
      {
        title: "操作",
        fixed: "right",
        render: (text, render) => {
          return (
            <div>
              {render.importStatus === 'Y' && <TheButton hasPermi={['commodity:library:publish']} onClick={() => this.onSubmit(render.productId)}>发布</TheButton>}
              <TheButton hasPermi={['commodity:library:detail']} onClick={() => this.props.history.push(`/commodity/list/detail/${render.productId}`)}>查看详情</TheButton>
              <TheButton hasPermi={['commodity:library:edit']} onClick={() => this.props.history.push(`/commodity/list/edit/${render.productId}`)}>编辑</TheButton>
              {/* <TheButton hasPermi={['commodity:library:delete']} onClick={() => this.delConfirm(render.productId)}>删除</TheButton> */}
            </div>
          );
        },
      },
    ],
    data: [],
    pageData: {
      pageNo: 1,
      pageSize: 10,
    },
    total: 0,
    loading: false
  };
  async componentDidMount() {
    console.log(localStorage.getItem("searchValue"),localStorage.getItem('pageNo'),localStorage.getItem('pageSize'))
    if(localStorage.getItem('searchValue') && localStorage.getItem('pageNo')&&localStorage.getItem('pageSize')){
      let search = JSON.parse(localStorage.getItem('searchValue'))
      this.setState({
        searchValue:search,
        pageData:{
          pageNo:localStorage.getItem('pageNo'),
          pageSize:localStorage.getItem('pageSize')
        }
      },async ()=>{
        await this.getData()
      })
    }else if(localStorage.getItem('pageNo')&&localStorage.getItem('pageSize')){
      this.setState({
        pageData:{
          pageNo:localStorage.getItem('pageNo'),
          pageSize:localStorage.getItem('pageSize')
        }
      },async ()=>{
        await this.getData()
      })
    }else if(localStorage.getItem('pageNo')){
      this.setState({
        pageData:{
          pageNo:localStorage.getItem('pageNo'),
          pageSize:10
        }
      },async ()=>{
        await this.getData()
      })
    }else{
      await this.getData()
    }
  }
  getData = async () => {
    this.setState({ loading: true })
    const { pageData, searchValue } = this.state
    let res = await apiGetCommodityList({ ...pageData, ...searchValue, reviewStatus: 'D' })
    if (res.data && res.code === 0) {
      this.setState({
        pageData: {
          pageNo: res.pageNo,
          pageSize: res.pageSize
        },
        total: res.totalCount,
        data: res.data,
        loading: false
      })
    }
  }
  onSubmit = (productId) => {
    React.$confirm({
      title: '您确定发布此商品吗？',
      onOk: async () => {
        let response = await apiProductInfoUpdateState({ productId, reviewStatus: 'S' })
        if (response.code === 0) {
          React.$message({
            type: 'info',
            content: '发布成功'
          })
          this.getData()
        }
      }
    })
  }
  pageChange = (pageNo, pageSize) => {
    this.setState({
      pageData: {
        pageNo, pageSize
      }
    }, () => {
      localStorage.setItem('pageNo',this.state.pageData.pageNo);
      localStorage.setItem('pageSize',this.state.pageData.pageSize);
      this.getData()
    })
  };
  delConfirm = (productId) => {
    React.$confirm({
      title: "您确认删除本条商品吗？",
      onOk: async () => {
        let res = await apiProductInfoDel({ productId })
        if (res.code === 0) {
          React.$message({
            type: 'info',
            content: '删除成功'
          })
          this.getData()
        }
      },
    });
  };
  setSearchValue = value => {
    this.setState({
      searchValue: value,
      pageData: {
        pageNo: 1,
        pageSize: 10
      }
    }, () => {
      this.getData()
      let search = JSON.stringify(this.state.searchValue)
      localStorage.setItem('searchValue',search)
      localStorage.setItem('pageNo',this.state.pageData.pageNo)
      localStorage.setItem('pageSize',this.state.pageData.pageSize);
    })
  }
  exportTable = async () => {
    let { searchValue } = this.state
    this.setState({
      exportLoading: true
    })
    let tH_data = [{ prop: 'productId', title: '商品ID' }, { prop: 'productName', title: '商品名称' },
    { prop: 'productClassifyName', title: '所属分类' }, { prop: 'originalPrice', title: '商品原价' ,valueType:'number'},
    { prop: 'currentPrice', title: '商品现价',valueType:'number' }, { prop: 'shenhestatus', title: '审核状态' },{ prop: 'importStatus', title: '补录状态' },
    { prop: 'updateTime', title: '创建时间' }]

    let res = await apiGetCommodityList({ pageNo:1,pageSize:99999, ...searchValue, reviewStatus: 'D' })
    if (res.code === 0) {
      let tB_data = res.data.map(item => {
        return {
          ...item,
          shenhestatus: '待审核',
          currentPrice: Number(item.currentPrice / 100).toFixed(2),
          originalPrice: Number(item.originalPrice / 100).toFixed(2),
          importStatus:item.importStatus==='N'?'需要补录':'不需要补录'
        }
      }),
        fileName = '商品库列表',
        isSheet = true
      exportSheetTable({ fileName, tH_data, tB_data, isSheet })
      this.setState({
        exportLoading: false
      })
    }
  }
  render() {
    const { columns, data, pageData, total, loading ,exportLoading} = this.state;
    return (
      <div className="p-layout-box commodity-examine">
        <div className="p-search-box">
          <SearchHeader setSearchValue={this.setSearchValue} exportSheet={this.exportTable} exportLoading={exportLoading} />
        </div>
        <div className="p-layout-content-pagination">
          <TheTable
            scroll={{ x: "max-content", y: '63vh' }}
            columns={columns}
            dataSource={data}
            loading={loading}
          />
          <ThePagination
            pageNo={pageData.pageNo}
            pageSize={pageData.pageSize}
            total={total}
            pageChange={this.pageChange}
          />
        </div>
      </div>
    );
  }
}

export default Library;
